﻿using BingSpatialDataServiceExcelAddin.BSDSTools.Models;
using System;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Controls;

namespace BingSpatialDataServiceExcelAddin.Views
{
    /// <summary>
    /// Interaction logic for DataSourceListBox.xaml
    /// </summary>
    public partial class DataSourceListBox : UserControl
    {
        public DataSourceListBox()
        {
            InitializeComponent();
        }

        private void DownloadBtn_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            Button b = sender as Button;
            DataSourceInfo ds = b.Tag as DataSourceInfo;

            InputBox inputBx = new InputBox();
            inputBx.Closing = (r, m) =>
            {
                if (r == System.Windows.Forms.DialogResult.OK)
                {
                    if (!string.IsNullOrWhiteSpace(m))
                    {
                        //Get output file
                        System.Windows.Forms.SaveFileDialog sfg = new System.Windows.Forms.SaveFileDialog()
                        {
                            RestoreDirectory = true,
                            Title = "Save Data Source",
                            DefaultExt = "xls",
                            Filter = "Excel Workbook (*.xls)|*.xls",
                        };

                        if (sfg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        {
                            //Open Download Panel and Start download
                            DownloadModal form = new DownloadModal();
                            form.Show(ds.QueryURL, m, ds.IsPublic, sfg.FileName);
                        //    (form.DownloadPanel as DownloadPanel).Download(ds.QueryURL, m, ds.IsPublic, sfg.FileName);
                        }
                    }
                    else
                    {
                        MessageBox.Show("Invalid Mster Key provided.");
                    }
                }
            };
            inputBx.Show("Enter Bing Maps Master Key:");
        }

        private void DeleteBtn_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            Button b = sender as Button;
            DataSourceInfo ds = b.Tag as DataSourceInfo;

            if (MessageBox.Show(string.Format("Delete {0}/{1} data source?", ds.Name, ds.EntityType),"Deleting Data Source", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {                
                InputBox inputBx = new InputBox();
                inputBx.Closing = (r, m) =>
                {
                    try
                    {
                        if (r == System.Windows.Forms.DialogResult.OK)
                        {
                            if (!string.IsNullOrWhiteSpace(m))
                            {
                                //Drop the entity ID from the Query URL
                                string url = ds.QueryURL.Remove(ds.QueryURL.LastIndexOf("/")) + "?key=" + m;
                                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                                request.Method = "DELETE";

                                using (WebResponse response = request.GetResponse())
                                {
                                    using (Stream rStream = response.GetResponseStream())
                                    {
                                    }
                                }

                                (this.DataContext as System.Collections.Generic.List<DataSourceInfo>).Remove(ds);

                                MessageBox.Show("Data source delete request sent to Bing.");
                            }
                            else
                            {
                                MessageBox.Show("Invalid Mster Key provided.");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error deleting data source:\r\n" + ex.Message);
                    }
                };
                inputBx.Show("Enter Bing Maps Master Key:");                
            }
        }

        private void IsPublic_Checked(object sender, System.Windows.RoutedEventArgs e)
        {
            InputBox inputBx = new InputBox();
            inputBx.Closing = (r, m) =>
            {
                if (r == System.Windows.Forms.DialogResult.OK)
                {
                    if (!string.IsNullOrWhiteSpace(m))
                    {
                        CheckBox b = sender as CheckBox;
                        DataSourceInfo ds = b.Tag as DataSourceInfo;
                        bool makePublic = ds.IsPublic;

                        if (!ds.IsPublic)
                        {
                            if (MessageBox.Show("Make Data Source Private?", "Make Private", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                            {
                                makePublic = false;
                            }
                        }
                        else
                        {
                            if (MessageBox.Show("Make Data Source Public?", "Make Public", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                            {
                                makePublic = true;
                            }
                        }

                        if (ds.IsPublic != makePublic)
                        {
                            //TODO: consider monitoring change of public setting.
                            WebClient wc = new WebClient();
                            wc.DownloadString("https://spatial.virtualearth.net/REST/v1/data/accessID/dataSourceName/$updateDataSource?setPublic=" + ((makePublic) ? "1" : "0") + "&key=" + m);
                            ds.IsPublic = makePublic;

                            MessageBox.Show("Request sent to Bing to make data source " + ((makePublic) ? "Public" : "Private"));
                        }
                    }
                    else
                    {
                        MessageBox.Show("Invalid Mster Key provided.");
                    }
                }
            };
            inputBx.Show("Enter Bing Maps Master Key:");
        }
    }
}
